package com.leyou.search.service;

import com.fasterxml.jackson.core.type.TypeReference;
import com.leyou.client.ItemClient;
import com.leyou.common.utils.BeanHelper;
import com.leyou.common.utils.JsonUtils;

import com.leyou.search.pojo.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class IndexService {

    @Autowired
    private ItemClient itemClient;

    /**
     * 数据装换的逻辑
     *
     * @param spuDTO
     * @return
     */
    public Goods buildGoods(SpuDTO spuDTO) {
        Goods goods = BeanHelper.copyProperties(spuDTO, Goods.class);
//   "skus": null,
//   "price": null,
        List<SkuDTO> skuDTOS = itemClient.querySkuBySpuId(spuDTO.getId());
        HashSet<Long> prices = new HashSet<>();
        List<Map<String, Object>> skuList = new ArrayList<>();
        skuDTOS.forEach(skuDTO ->
        {
            prices.add(skuDTO.getPrice());
            Map<String, Object> map = new HashMap<>();
            map.put("id", skuDTO.getId());
            map.put("price", skuDTO.getPrice());
            map.put("title", skuDTO.getTitle());
            map.put("image", skuDTO.getImages().split(",")[0]);
            skuList.add(map);
        });
        goods.setSkus(JsonUtils.toString(skuList));
        goods.setPrice(prices);
//   "all": null,
        String names = itemClient.queryByIds(spuDTO.getCategoryIds()).stream().map(CategoryDTO::getName).collect(Collectors.joining(" "));
        String name1 = itemClient.queryById(spuDTO.getBrandId()).getName();
        goods.setAll(spuDTO.getName() + " " + names + " " + name1);
//   "categoryId": null,
        goods.setCategoryId(spuDTO.getCid3());
//   "createTime": null,
        goods.setCreateTime(spuDTO.getCreateTime().getTime());


//   "specs": null*/
        HashMap sepcs = new HashMap();
        List<SpecParamDTO> specParamDTOS = itemClient.querySpecParams(null, spuDTO.getCid3(), true);
        SpuDetailDTO spuDetailDTO = itemClient.querySpuDetailById(spuDTO.getId());

        Map<Long, Object> genericSpec = JsonUtils.nativeRead(spuDetailDTO.getGenericSpec(), new TypeReference<Map<Long, Object>>() {
        });
        Map<Long, List<String>> specialSpec = JsonUtils.nativeRead(spuDetailDTO.getSpecialSpec(), new TypeReference<Map<Long, List<String>>>() {
        });

        specParamDTOS.forEach(specParam ->
        {
            Long id = specParam.getId();
            String name = specParam.getName();

            Object value = null;
            if (specParam.getGeneric()) {
                value = genericSpec.get(id);
            } else {
                value = specialSpec.get(id);
            }
            // 判断是否是数值类型
            if(specParam.getNumeric()){
                // 是数字类型，分段
                value = chooseSegment(value, specParam);
            }
            sepcs.put(name,value);
        });
        goods.setSpecs(sepcs);

        return goods;
    }

    private String chooseSegment(Object value, SpecParamDTO p) {
        if (value == null || StringUtils.isBlank(value.toString())) {
            return "其它";
        }
        double val = parseDouble(value.toString());
        String result = "其它";
        // 保存数值段
        for (String segment : p.getSegments().split(",")) {
            String[] segs = segment.split("-");
            // 获取数值范围
            double begin = parseDouble(segs[0]);
            double end = Double.MAX_VALUE;
            if (segs.length == 2) {
                end = parseDouble(segs[1]);
            }
            // 判断是否在范围内
            if (val >= begin && val < end) {
                if (segs.length == 1) {
                    result = segs[0] + p.getUnit() + "以上";
                } else if (begin == 0) {
                    result = segs[1] + p.getUnit() + "以下";
                } else {
                    result = segment + p.getUnit();
                }
                break;
            }
        }
        return result;
    }

    private double parseDouble(String str) {
        try {
            return Double.parseDouble(str);
        } catch (Exception e) {
            return 0;
        }
    }

}
